require 'sketchup.rb'

# interface routine
def convert_2_cpl

	# globals
	vertices = Array.new
	faces = Array.new
	
	# iterate through each entity in the model
	Sketchup.active_model.entities.each do |entity|
		collect_entities(entity, vertices, faces)
	end
	
	# write data to file
	file = UI.savepanel("Save to CPL", "", "model.cpl")
	#UI.messagebox(file)
	#file = File.expand_path("~") + "/Desktop/model.txt"
	outf = File.open(file, "w")
	
	# write out header section
  outf << "cpl" << "\n"
	outf << "vertices " << vertices.length << "\n"
	outf << "polygons " << faces.length << "\n"
  outf << "---8<---" << "\n"
	
	# iterate the vertices
	vertices.each do |vert|
    points = vert.position.to_a
    outf << points[0]*0.0254 << " "
		outf << points[1]*0.0254 << " "
		outf << points[2]*0.0254 << "\n"
	end
	
	# iterate faces
	faces.each do |face|
		outf << face.edges.length << " "
		
		# temp array to store this face's vertices
		face_vertices = Array.new
		
		# get the index of each vertex connected to this face
		face.vertices.each do |vert|
		
			# get this vertex's index
			idx = vertices.index(vert)
			if not idx.nil? then face_vertices << idx end
			
		end
    
    face_color = get_face_color(face)
    outf << face_color[0] << " "
    outf << face_color[1] << " "
    outf << face_color[2] << " "
    
		face_vertices.each do |idx|
			outf << idx << " "
		end
		
		outf << "\n"
		
	end
	
	# close the file
	outf.close
	
end

def get_face_color(face)
  if face.material != nil then
    c = face.material.color
    return [c.red, c.green, c.blue]
  end
  if face.back_material != nil then
    c = face.back_material.color
    return [c.red, c.green, c.blue]
  end
  return [255,0,255]
end

# collect entities in the model
def collect_entities(entity, vertices, faces)

	case entity
	
	when Sketchup::Edge
		vertices.replace(vertices | entity.vertices)
	
	when Sketchup::Face
		faces << entity
	
	when  Sketchup::Group
		entity.entities.each do |gpe|
			collect_entities(gpe, vertices, faces)
		end
	end
		
end

if( not file_loaded?("skp2cpl.rb") )

    add_separator_to_menu("Plugins")

    UI.menu("Plugins").add_item("Save as CPL") { convert_2_cpl }

end

#-----------------------------------------------------------------------------
file_loaded("skp2cpl.rb")
